package com.qiudaozhang.loveblog.controller;

import com.qiudaozhang.loveblog.entity.Article;
import com.qiudaozhang.loveblog.entity.Category;
import com.qiudaozhang.loveblog.entity.Tag;
import com.qiudaozhang.loveblog.pojo.ResponseCode;
import com.qiudaozhang.loveblog.service.ArticleService;
import com.qiudaozhang.loveblog.service.CategoryService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 邱道长
 * 2019/11/13
 */
@Controller
@RequestMapping("article")
public class ArticleController {


    @Resource
    private ArticleService articleService;

    @Resource
    private CategoryService categoryService;

    /**
     * 添加一篇文章
     *
     * @param article
     * @return
     */
    @PostMapping
    @ResponseBody
    public ResponseCode post(@RequestBody  Article article , HttpSession session) {
        Object writeId = session.getAttribute("writeId");
        ResponseCode code = new ResponseCode();
        System.out.println(article);
        if(writeId == null){
            // 第一次发表
            articleService.post(article);
            code.setStatus(ResponseCode.SUCCESS);
            code.setMsg("发表文章成功！");
            session.setAttribute("writeId",article.getId());
        } else {
            article.setId(Long.parseLong(writeId.toString()));
            article.setUpdated(LocalDateTime.now());
            articleService.update(article);
            code.setStatus(ResponseCode.SUCCESS);
            code.setMsg("更新文章成功！");
        }
        return code;
    }

    @GetMapping("{id}")
    public String findById(@PathVariable("id") Long id, Model model) {
        Article article = articleService.findById(id);
        model.addAttribute("article", article);
        return "article";
    }


    @GetMapping("write")
    public String write(HttpSession session,Model model) {
        session.removeAttribute("writeId");
        // 分类信息获取
        List<Category> categories = categoryService.findAll();
        model.addAttribute("categories",categories);
        return "write";
    }

}
